
package net.swa.dewei.web.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Required;
import net.swa.dewei.beans.entity.BatteryPrice;
import net.swa.dewei.beans.entity.CheXing;
import net.swa.dewei.beans.entity.District;
import net.swa.dewei.beans.vo.VoBattery;
import net.swa.dewei.service.BatteryService;
import net.swa.system.beans.entity.Dict;
import net.swa.system.service.ICommonService;
import net.swa.system.util.annotation.Log;
import net.swa.system.web.action.AbstractBaseAction;
import net.swa.util.BuzConst;
import net.swa.util.DateUtils;
import net.swa.util.JsonResult;
import net.swa.util.StringUtil;

/**电池信息表 Action**/
public class BatteryPriceAction extends AbstractBaseAction
{
    private static final long serialVersionUID = -9167064623097370397L;

    private final Logger log = Logger.getLogger(BatteryPriceAction.class);

    /** 公用方法接口 */
    private ICommonService commonService;

    private BatteryService batteryService;

    private BatteryPrice model;

    /**电池类型**/
    private List<Dict> dianchiTypes;

    /**电池品牌**/
    private List<Dict> dianchiPinPais;

    /**省列表**/
    private List<District> provinceList;

    /**市列表*/
    private List<District> cityList;

    /**县区列表*/
    private List<District> areaList;

    private List<CheXing> chexingList;

    //实体类id
    private Long id;

    //id集合
    private Long[] ids;

    /**省**/
    private String province;

    /**市*/
    private String city;

    /**县**/
    private String town;

    /**品牌**/
    private String pinPai;

    /**型号**/
    private String xingHao;

    private File file;

    private String fileFileName;

    /**初始化分页查询**/
    @Log(description = "初始化电池分页查询")
    public String listPage()
    {
        dianchiTypes = commonService.search("title", "电池型号", Dict.class, null, "dictPaixu", "asc");
        dianchiPinPais = commonService.search("title", "电池品牌", Dict.class, null, "dictPaixu", "asc");
        provinceList = commonService.search("pid", "0", District.class, null, "sort", "asc");
        return "listPage";
    }

    /**
     * 查询价格列表信息
     * @throws Exception */
    public String queryList() throws Exception
    {
        currentPage = currentPage == 0 ? 1 : currentPage;
        pageSize = pageSize == 0 ? 20 : pageSize;
        JsonResult<BatteryPrice> json = null;
        json = batteryService.queryPricePage(province, city, town, pinPai, xingHao, currentPage, pageSize, orderBy, orderType);
        json.setCurrentPage(currentPage);
        json.setSuccess(true);
        outJson(json);
        return null;
    }

    @Log(description = "去新增或者修改电池价格")
    public String toAddBatteryPrice() throws Exception
    {
        dianchiTypes = commonService.search("title", "电池型号", Dict.class, null, "dictPaixu", "asc");
        dianchiPinPais = commonService.search("title", "电池品牌", Dict.class, null, "dictPaixu", "asc");
        provinceList = commonService.search("pid", "0", District.class, null, "sort", "asc");
        if (null != id)
        {
            model = batteryService.queryPriceById(id);
            cityList = commonService.search(District.class, new String[] { "pname", "level" }, new Object[] { model.getProvince(), 2 });
            areaList = commonService.search(District.class, new String[] { "pname", "level" }, new Object[] { model.getCity(), 3 });
        }
        else
        {
            model = new BatteryPrice();
        }
        return "toAddBatteryPrice";
    }

    @Log(description = "新增或者编辑电池价格")
    public String saveBatteryPrice() throws Exception
    {
        JsonResult<Object> json = null;
        if (null == model.getId())
        {
            model.setCrateDate(DateUtils.getCurrDate(null));
            model.setUpdateDate(DateUtils.getCurrDate(null));

            log.debug("电池价格新增：" + model);
            json = batteryService.saveBatteryPrice(model);
        }
        else
        {
            log.debug("电池价格修改：" + model);
            model.setUpdateDate(DateUtils.getCurrDate(null));
            json = batteryService.updateBatteryPrice(model);
        }
        if (null == json)
        {
            outError("系统异常");
        }
        else
        {
            outJson(json);
        }
        return null;
    }

    /** * 删除方法**/
    @Log(description = "删除电池")
    public String delete() throws Exception
    {
        batteryService.deletePrices(ids);
        outSuccess();
        return null;
    }

    @Log(description = "进入电池综合查询")
    public String queryBetteryTotal()
    {
        dianchiTypes = commonService.search("title", "电池型号", Dict.class, null, "dictPaixu", "asc");
        dianchiPinPais = commonService.search("title", "电池品牌", Dict.class, null, "dictPaixu", "asc");
        provinceList = commonService.search("pid", "0", District.class, null, "sort", "asc");
        chexingList = commonService.search("state", BuzConst.CHEXING_STATE_SHOW, CheXing.class, null, "sort", "asc");
        return "queryBetteryTotal";
    }

    @Log(description = "电池综合查询数据")
    public String queryBetteryAllPage() throws Exception
    {
        currentPage = currentPage == 0 ? 1 : currentPage;
        pageSize = pageSize == 0 ? 20 : pageSize;
        JsonResult<VoBattery> json = null;
        if (StringUtils.isBlank(province))
        {
            json = batteryService.queryPageByPinpXinghChex(null, null, null, pinPai, xingHao, id, currentPage, pageSize, orderBy, orderType);
        }
        else
        {

            json = batteryService.queryPageByPinpXinghChex(province, city, town, pinPai, xingHao, id, currentPage, pageSize, orderBy, orderType);
        }
        json.setCurrentPage(currentPage);
        json.setSuccess(true);
        outJson(json);
        return null;
    }

    public String exportExcel()
    {
        //根据多条件导出
        HSSFWorkbook workbook = batteryService.exportExcel(province, city, town, pinPai, xingHao);
        HttpServletResponse response = getResponse();
        BufferedOutputStream bos = null;
        try
        {
            response.setContentType("application/vnd.ms-excel");
            String filename = new String("filename".getBytes("gbk"), "iso-8859-1") + ".xls";
            response.setHeader("Content-disposition", "attachment;filename=" + filename);
            bos = new BufferedOutputStream(response.getOutputStream());
            workbook.write(bos);
            bos.flush();
            removeSessionAttribute("listSheet");
        }
        catch (Exception e)
        {
            e.printStackTrace();
            log.debug("门店导出出错：" + e);
        }
        finally
        {
            try
            {
                bos.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
                log.debug("门店导出出错,关闭bos：" + e);
            }
        }
        return null;
    }

    public String exportTemplate()
    {
        String path = getSession().getServletContext().getRealPath("/templates/batteryprice.xls");
        BufferedOutputStream bos = null;
        try
        {
            HttpServletResponse response = getResponse();
            // path是指欲下载的文件的路径。 
            File file = new File(path);
            // 取得文件名。
            String filename = file.getName();
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            response.setContentType("application/octet-stream");

            bos = new BufferedOutputStream(response.getOutputStream());
            bos.write(buffer);
            bos.flush();
            bos.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                bos.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
                log.debug("门店导出出错,关闭bos：" + e);
            }
        }
        return null;
    }
    
    public String exportErrorFile(){
        String path = getSession().getServletContext().getRealPath("/templates/batteryprice.xls");
        if(!StringUtils.isBlank(fileFileName)){
            path = fileFileName;
        }
        BufferedOutputStream bos = null;
        try
        {
            HttpServletResponse response = getResponse();
            // path是指欲下载的文件的路径。 
            File file = new File(path);
            // 取得文件名。
            String filename = file.getName();
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            response.setContentType("application/octet-stream");

            bos = new BufferedOutputStream(response.getOutputStream());
            bos.write(buffer);
            bos.flush();
            bos.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                bos.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
                log.debug("门店导出出错,关闭bos：" + e);
            }
        }
        return null;
    }

    public String toImpPriceExcel()
    {

        return "import";
    }

    public String impPriceExcel() throws Exception
    {
        Map<String, Object> map = null;
        String errFilePath = ServletActionContext.getServletContext().getRealPath("/uploads/error/");
        if (null != file && (!file.toString().equals("")))
        {
            String path = uploadFile();
            if (!StringUtils.isBlank(path))
            {
                map = batteryService.addExcel(path,errFilePath);
            }else{
                map = new HashMap<String, Object>();
                map.put("success", false);
                map.put("message", "文件上传失败");
            }
        }
        else
        {
            map = new HashMap<String, Object>();
            map.put("success", false);
            map.put("message", "请选择按模板格式的文件上传");
        }
        outJson(map);
        return null;
    }

    /**
     * 上传文件
     * @return
     */
    private String uploadFile()
    {
        String code = StringUtil.getRandomString(5) + System.currentTimeMillis();
        String realpath = ServletActionContext.getServletContext().getRealPath("/uploads/");
        try
        {
            File saveFile = new File(new File(realpath), fileFileName.substring(0, fileFileName.length() - 4) + code + ".xls");
            if (saveFile.exists())
            {
                saveFile.delete();
            }
            file.renameTo(saveFile);
            return realpath + File.separator + fileFileName.substring(0, fileFileName.length() - 4) + code + ".xls";
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return "false";
    }

    public ICommonService getCommonService()
    {
        return commonService;
    }

    @Required
    @Resource
    public void setCommonService(ICommonService commonService)
    {
        this.commonService = commonService;
    }

    public BatteryService getBatteryService()
    {
        return batteryService;
    }

    @Required
    @Resource
    public void setBatteryService(BatteryService batteryService)
    {
        this.batteryService = batteryService;
    }

    public BatteryPrice getModel()
    {
        return model;
    }

    public void setModel(BatteryPrice model)
    {
        this.model = model;
    }

    public List<Dict> getDianchiTypes()
    {
        return dianchiTypes;
    }

    public void setDianchiTypes(List<Dict> dianchiTypes)
    {
        this.dianchiTypes = dianchiTypes;
    }

    public List<Dict> getDianchiPinPais()
    {
        return dianchiPinPais;
    }

    public void setDianchiPinPais(List<Dict> dianchiPinPais)
    {
        this.dianchiPinPais = dianchiPinPais;
    }

    public Long getId()
    {
        return id;
    }

    public void setId(Long id)
    {
        this.id = id;
    }

    public Long[] getIds()
    {
        return ids;
    }

    public void setIds(Long[] ids)
    {
        this.ids = ids;
    }

    public static long getSerialversionuid()
    {
        return serialVersionUID;
    }

    public String getProvince()
    {
        return province;
    }

    public void setProvince(String province)
    {
        this.province = province;
    }

    public String getCity()
    {
        return city;
    }

    public void setCity(String city)
    {
        this.city = city;
    }

    public String getTown()
    {
        return town;
    }

    public void setTown(String town)
    {
        this.town = town;
    }

    public String getPinPai()
    {
        return pinPai;
    }

    public void setPinPai(String pinPai)
    {
        this.pinPai = pinPai;
    }

    public String getXingHao()
    {
        return xingHao;
    }

    public void setXingHao(String xingHao)
    {
        this.xingHao = xingHao;
    }

    public List<District> getProvinceList()
    {
        return provinceList;
    }

    public void setProvinceList(List<District> provinceList)
    {
        this.provinceList = provinceList;
    }

    public List<District> getCityList()
    {
        return cityList;
    }

    public void setCityList(List<District> cityList)
    {
        this.cityList = cityList;
    }

    public List<District> getAreaList()
    {
        return areaList;
    }

    public void setAreaList(List<District> areaList)
    {
        this.areaList = areaList;
    }

    public List<CheXing> getChexingList()
    {
        return chexingList;
    }

    public void setChexingList(List<CheXing> chexingList)
    {
        this.chexingList = chexingList;
    }

    public File getFile()
    {
        return file;
    }

    public void setFile(File file)
    {
        this.file = file;
    }

    public String getFileFileName()
    {
        return fileFileName;
    }

    public void setFileFileName(String fileFileName)
    {
        this.fileFileName = fileFileName;
    }

    
}
